using System.IO;
using System.Reflection;
using ContentRenderingApi.Exceptions;

namespace ContentRenderingApi
{
    /// <summary/>
    public class EmbeddedResourceTemplate : AbstractTemplate
    {
        private Assembly _assembly;
        private string _nameSpace;

        /// <summary/>
        public EmbeddedResourceTemplate(
            Assembly assembly,
            string nameSpace,
            string name) : base(name)
        {
            this._assembly = assembly;
            this._nameSpace = nameSpace;
        }

        /// <summary/>
        protected override string LoadTemplate(string name)
        {
            // build the partial name of the template
            string partialName = name.Replace(
                Constant.TEMPLATE_SEPARATOR,
                Constant.RESOURCE_SEPARATOR);

            // build the full name of the template
            string fullName = string.Format(
                Constant.FULL_NAME_JOIN,
                this._nameSpace,
                partialName);

            // load the resource by its full name 
            using(Stream stream = this._assembly.GetManifestResourceStream(fullName))
            {
                // if the load failed ... indicate it
                if (stream == null)
                {
                    throw new TemplateDoesNotExistException(fullName);
                }
                
                // the stream reader will detect the streams encoding ... thats why its being used
                using(StreamReader streamReader = new StreamReader(stream))
                {
                    return streamReader.ReadToEnd();
                }
            }
        }
    }
}
